package com.usdt.web.controller.cp.salesTools;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.usdt.common.core.domain.R;
import com.usdt.system.domain.req.CallbackRecordReqVO;
import com.usdt.system.domain.req.TransferOutReqVO;
import com.usdt.system.domain.req.VisitRecordReqVO;
import com.usdt.system.domain.req.VisitRegisterListExportReqVO;
import com.usdt.system.domain.req.VisitRegisterReqVO;
import com.usdt.system.domain.resp.VisitRegisterListRespVO;
import com.usdt.system.domain.resp.VisitRegisterRespVO;
import com.usdt.system.dto.cp.VisitRegisterListExcelDTO;
import com.usdt.system.service.cp.VisitRegisterService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 到访登记 前端控制器
 * </p>
 *
 * @author L
 * @since 2025-10-04
 */
@RestController
@RequestMapping("/visitRegister")
@Slf4j
@Tag(name = "到访登记")
public class VisitRegisterController {

	@Autowired
	private VisitRegisterService visitRegisterService; 
	
    @GetMapping("/list")
    @Operation(summary ="列表")
    public R<IPage<VisitRegisterListRespVO>> list(
    		@Schema(description = "客户渠道")@RequestParam(value = "clueSource", required = false) String clueSource,
    		@Schema(description = "关键词")@RequestParam(value = "keyWord", required = false) String keyWord,
    		@Schema(description = "开始日期（yyyy-MM-dd）")@RequestParam(value = "startDate", required = false) String startDate,
    		@Schema(description = "结束日期（yyyy-MM-dd）")@RequestParam(value = "endDate", required = false) String endDate,
    		@Schema(description = "客户状态")@RequestParam(value = "customerTatus", required = false) String customerStatus,
    		@Schema(description = "业务员")@RequestParam(value = "userId", required = false) String userId,
    		@Schema(description = "页码")@RequestParam(value = "pageNum", required = false) Integer pageNum,
    		@Schema(description = "每页显示记录数")@RequestParam(value = "pageSize", required = false) Integer pageSize
    		) {
    	
    	return R.ok(visitRegisterService.list(clueSource,keyWord,startDate,endDate,customerStatus,userId,pageNum,pageSize));
    }

    @PostMapping("/insert")
    @Operation(summary ="新增")
    public R<Boolean> insert(@RequestBody @Valid VisitRegisterReqVO vo) {
    	
    	return R.ok(visitRegisterService.insert(vo));
    }
    
    @GetMapping("/detail/{id}")
    @Operation(summary ="详情")
    public R<VisitRegisterRespVO> insert(@Schema(description = "到访登记id")@PathVariable(value = "id", required = true) Integer id) {
    	
    	return R.ok(visitRegisterService.detail(id));
    }
    
    @Operation(summary ="修改")
	@PostMapping("/update/{id}")
	public R<Integer> update(
			@Schema(description = "线索登记id")@PathVariable(value = "id", required = true)Integer id,
			@RequestBody @Valid VisitRegisterReqVO vo) {
    	
    	return R.ok(visitRegisterService.update(id, vo));
	}
    
    @Operation(summary ="转出")
 	@PostMapping("/transferOut/{id}")
 	public R<Boolean> transferOut(
 			@Schema(description = "到访登记id")@PathVariable(value = "id", required = true)Integer id,
 			@RequestBody @Valid TransferOutReqVO vo) {
     	
     	return R.ok(visitRegisterService.transferOut(id, vo));
 	}
    
    @Operation(summary ="到访记录")
 	@PostMapping("/visitRecord/{id}")
 	public R<Boolean> visitRecord(
 			@Schema(description = "到访登记id")@PathVariable(value = "id", required = true)Integer id,
 			@RequestBody @Valid VisitRecordReqVO vo) {
     	
     	return R.ok(visitRegisterService.visitRecord(id,vo));
 	}
    
    @Operation(summary ="回访记录")
 	@PostMapping("/callbackRecord/{id}")
 	public R<Boolean> callbackRecord(
 			@Schema(description = "到访登记id")@PathVariable(value = "id", required = true)Integer id,
 			@RequestBody @Valid CallbackRecordReqVO vo) {
     	
     	return R.ok(visitRegisterService.callbackRecord(id,vo));
 	}
    
    @PostMapping("/list/export")
    @Operation(summary ="导出-列表")
    public void listExport(
    		HttpServletResponse response,
    		@RequestBody VisitRegisterListExportReqVO vo) throws IOException {
    	
    	List<VisitRegisterListExcelDTO> list = visitRegisterService.listExport(vo);
    	exportActivityExcel(response,list,VisitRegisterListExcelDTO.class,"到访登记表","到访信息");
    }
    
    public void exportActivityExcel(HttpServletResponse response, List dataList, Class clazz
    		,String excelName,String sheetName) throws IOException {
        // 1. 设置响应头（关键：避免中文乱码、指定文件类型）
    	response.addHeader("Pargam", "no-cache");
    	response.addHeader("Cache-Control", "no-cache");
    	response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        //response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); // Excel 2007+格式
    	//response.setContentType("application/octet-stream;charset=UTF-8"); // Excel 2007+格式
        response.setCharacterEncoding("utf-8");
        // 文件名编码：使用URLEncoder避免中文乱码，替换“+”为“%20”（浏览器兼容）
        String fileName = URLEncoder.encode(excelName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName + ".xlsx");

        // 2. 使用EasyExcel写入数据（try-with-resources自动关闭ExcelWriter）
        try (var excelWriter = EasyExcel.write(response.getOutputStream(), clazz).build()) {
            // 3. 构建Sheet（指定工作表名称，如“活动信息”）
            var sheet = EasyExcel.writerSheet(sheetName).build();
            // 4. 写入数据（将实体类列表映射为Excel行）
            excelWriter.write(dataList, sheet);
        }
    }
}
